package com.chaofan.kings_poster.util;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Chaofan at 2019/1/28 15:17
 * email:chaofan2685@qq.com
 **/
public class JsonUtil {

    public static <T> T getBean(String json, Class<T> bean, String child){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            JsonNode node = mapper.readTree(json);
            if (StrUtil.isNotEmpty(child)){
                node = node.get(child);
            }
            return mapper.convertValue(node,bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T getBean(String json, Class<T> bean){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            JsonNode node = mapper.readTree(json);
            return mapper.convertValue(node,bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> getListBean(String json, Class<T> bean, String child){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<T> list = new ArrayList<>();
        try {
            JsonNode node = mapper.readTree(json);
            if (StrUtil.isNotEmpty(child)){
                node = node.get(child);
            }
            for (JsonNode objNode : node){
                list.add(mapper.convertValue(objNode,bean));
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static <T> List<T> getListBean(String json, Class<T> bean){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<T> list = new ArrayList<>();
        try {
            JsonNode node = mapper.readTree(json);
            for (JsonNode objNode : node){
                list.add(mapper.convertValue(objNode,bean));
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}
